import axios from 'axios'
import { ElMessage as Message, ElLoading as Loading } from 'element-plus'
import qs from 'qs'

let loadingInstance

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// create an axios instance
const service = axios.create({
  baseURL: process.env.NODE_ENV == 'production' ? '' : '/api',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
})

service.defaults.headers['Content-Type'] = 'application/json'

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    let meta = Object.assign({ showLoading: true }, config.meta)
    // showLoading 不为false 时 显示loading
    if (meta.showLoading) {
      loadingInstance = Loading.service({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)',
      })
    }

    if (config.method === 'get') {
      config.params = Object.assign(config.params || {}, {
        timeVersion: Date.now(),
      })
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }

    return config
  },
  (error) => {
    // do something with request error
    console.error(error) // for debug
    if (loadingInstance) loadingInstance.close()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  res => res
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (res) => {
    if (loadingInstance) loadingInstance.close()
    const status = res.status
    const data = res.data

    if (status !== 200) {
      Message({
        message: '网络错误，状态码：' + status,
        dangerouslyUseHTMLString: true,
        type: 'error',
      })
      console.error(res)
      return Promise.reject(res)
    }

    if (data instanceof Blob && data.type == 'application/json') {
      let reader = new FileReader()
      reader.onload = () => {
        let content = reader.result
        Message({
          message: content.message || '服务器内部错误',
          dangerouslyUseHTMLString: true,
          type: 'error',
        })
        console.error(res)
      }
      reader.readAsText(data)
      return Promise.reject(res)
    }

    const message = data.message
    if (data.resultCode == 400 || data.resultCode == 409) {
      Message({
        message: message || '业务冲突',
        dangerouslyUseHTMLString: true,
        type: 'error',
      })
      console.error(res)
      return Promise.reject(res)
    }
    if (data.resultCode == 500) {
      Message({
        message: message || '服务器内部错误',
        dangerouslyUseHTMLString: true,
        type: 'error',
      })
      console.error(res)
      return Promise.reject(res)
    }
    return res
  },
  (error) => {
    if (loadingInstance) loadingInstance.close()
    Message({
      message: '请求失败！',
      dangerouslyUseHTMLString: true,
      type: 'error',
    })
    console.error(error)
    return Promise.reject(error)
  }
)

export default service
